package com.example.other.netty.adpacket;

import com.example.other.netty.endecode.LoginUtil;
import com.example.other.netty.endecode.MessageRequestPacket;
import com.example.other.netty.endecode.PacketCodec;
import com.example.other.netty.imdemo.IMClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.util.Scanner;

public class IMClient {
    public static void main(String[] args) {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel socketChannel) {
                        socketChannel.pipeline().addLast(new FirstClientHandler());
                    }
                });
        bootstrap.connect("127.0.0.1", 8088).addListener(future -> {
            if(future.isSuccess()){
                System.out.println("Client连接成功。。。");
                //连接成功后，启动控制台线程
                startConsoleThread(((ChannelFuture)future).channel());
            }else{
                System.out.println("Client连接失败。。。");
            }
        });
    }

    private static void startConsoleThread(Channel channel) {
        new Thread(()->{//开启线程
            while (!Thread.interrupted()){
                if(LoginUtil.hasLogin(channel)){//判断是否登录成gong
                    System.out.println("输入消息发送至服务端");
                    Scanner sc = new Scanner(System.in);
                    String line = sc.nextLine();

                    MessageRequestPacket packet = new MessageRequestPacket();
                    packet.setMessage(line);
                    ByteBuf byteBuf = PacketCodec.encode(channel.alloc().buffer(), packet);
                    channel.writeAndFlush(byteBuf);
                }
            }
        }).start();
    }
}
